<template>
  <div class="page-container">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="$router.push('/dashboard/businesses')" link>
          <el-icon><Back /></el-icon> 返回列表
        </el-button>
        <h2>业务详情</h2>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleEdit">
          <el-icon><Edit /></el-icon> 编辑
        </el-button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <!-- 详情信息 -->
    <div v-else class="detail-wrapper">
      <!-- 基本信息 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <h3>基本信息</h3>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="业务编号">{{ businessDetail.businessCode }}</el-descriptions-item>
          <el-descriptions-item label="业务名称">{{ businessDetail.businessName }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ businessDetail.customerName }}</el-descriptions-item>
          <el-descriptions-item label="业务类型">{{ businessDetail.businessTypeName }}</el-descriptions-item>
          <el-descriptions-item label="负责人">{{ businessDetail.responsibleEmployeeName }}</el-descriptions-item>
          <el-descriptions-item label="业务状态">
            <el-tag :type="getStatusTagType(businessDetail.businessStatus)">
              {{ businessDetail.businessStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="业务金额">¥{{ formatMoney(businessDetail.businessAmount) }}</el-descriptions-item>
          <el-descriptions-item label="优先级">
            <span :class="`priority-tag ${getPriorityClass(businessDetail.priority)}`">
              {{ businessDetail.priority }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ businessDetail.startDate }}</el-descriptions-item>
          <el-descriptions-item label="结束日期">{{ businessDetail.endDate || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(businessDetail.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(businessDetail.updatedAt) }}</el-descriptions-item>
          <el-descriptions-item label="业务描述" :span="2">
            {{ businessDetail.description || '暂无描述' }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 业务进度 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <h3>业务进度</h3>
            <el-button type="primary" @click="handleUpdateProgress" size="small">
              <el-icon><Edit /></el-icon> 更新进度
            </el-button>
          </div>
        </template>
        <div v-if="businessDetail.progressNotes" class="progress-content">
          {{ businessDetail.progressNotes }}
        </div>
        <el-empty v-else description="暂无进度记录" />
      </el-card>

      <!-- 关联工单 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <h3>关联工单</h3>
            <el-button type="primary" @click="handleCreateWorkOrder" size="small">
              <el-icon><Plus /></el-icon> 创建工单
            </el-button>
          </div>
        </template>
        <el-table :data="relatedWorkOrders" style="width: 100%" v-loading="workOrdersLoading">
          <el-table-column prop="orderCode" label="工单编号" width="120" />
          <el-table-column prop="title" label="工单标题" min-width="180" />
          <el-table-column prop="orderType" label="工单类型" width="120" />
          <el-table-column prop="priority" label="优先级" width="80">
            <template #default="{ row }">
              <span :class="`priority-tag ${getPriorityClass(row.priority)}`">{{ row.priority }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getWorkOrderStatusType(row.status)">{{ row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="assignedEmployeeName" label="处理人" width="100" />
          <el-table-column prop="createdAt" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="viewWorkOrder(row)">
                <el-icon><View /></el-icon> 查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div v-if="!relatedWorkOrders.length && !workOrdersLoading" class="no-data">
          <el-empty description="暂无关联工单" />
        </div>
      </el-card>
    </div>

    <!-- 更新进度弹窗 -->
    <el-dialog v-model="progressDialogVisible" title="更新业务进度" width="500px">
      <el-form :model="progressForm" ref="progressFormRef">
        <el-form-item label="进度备注" prop="progressNotes">
          <el-input 
            v-model="progressForm.progressNotes" 
            type="textarea" 
            :rows="5"
            placeholder="请输入业务进度备注" 
          />
        </el-form-item>
        <el-form-item label="业务状态" prop="businessStatus">
          <el-select v-model="progressForm.businessStatus" placeholder="请选择业务状态">
            <el-option label="待处理" value="待处理" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="progressDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProgress" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { 
  getBusiness, 
  updateBusinessStatus, 
  updateBusinessProgress 
} from '@/api/businesses';
import { getWorkOrders, createWorkOrder } from '@/api/workOrders';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';

const route = useRoute();
const router = useRouter();
const businessId = ref(null);
const businessDetail = ref({});
const relatedWorkOrders = ref([]);
const loading = ref(true);
const workOrdersLoading = ref(false);
const submitLoading = ref(false);

// 更新进度弹窗
const progressDialogVisible = ref(false);
const progressFormRef = ref();
const progressForm = reactive({
  businessStatus: '',
  progressNotes: ''
});

// 获取业务详情
const getBusinessDetail = async () => {
  try {
    loading.value = true;
    const response = await getBusiness(businessId.value);
    if (response.code === 200) {
      businessDetail.value = response.data;
    }
  } catch (error) {
    console.error('获取业务详情失败:', error);
    ElMessage.error('获取业务详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取关联工单
const getRelatedWorkOrders = async () => {
  try {
    workOrdersLoading.value = true;
    const params = {
      businessId: businessId.value,
      page: 1,
      pageSize: 100
    };
    const response = await getWorkOrders(params);
    if (response.code === 200) {
      // 后端返回的数据结构是 { data: { data: [...], total: 10 } }
      let responseData = response.data;
      if (responseData && responseData.data && Array.isArray(responseData.data)) {
        relatedWorkOrders.value = responseData.data;
      } else if (responseData && Array.isArray(responseData)) {
        relatedWorkOrders.value = responseData;
      } else {
        console.warn('工单API返回的数据格式不正确:', responseData);
        relatedWorkOrders.value = [];
      }
    }
  } catch (error) {
    console.error('获取关联工单失败:', error);
    ElMessage.error('获取关联工单失败');
  } finally {
    workOrdersLoading.value = false;
  }
};

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 格式化金额
const formatMoney = (amount) => {
  return new Intl.NumberFormat('zh-CN').format(amount);
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    '待处理': 'info',
    '进行中': 'primary',
    '已完成': 'success',
    '已取消': 'danger'
  };
  return statusMap[status] || 'info';
};

// 获取工单状态类型
const getWorkOrderStatusType = (status) => {
  const statusMap = {
    '待处理': 'info',
    '处理中': 'primary',
    '待回单': 'warning',
    '已完成': 'success',
    '已关闭': 'info'
  };
  return statusMap[status] || 'info';
};

// 获取优先级样式类
const getPriorityClass = (priority) => {
  const priorityMap = {
    '低': 'low',
    '中': 'medium', 
    '高': 'high',
    '紧急': 'urgent'
  };
  return priorityMap[priority] || 'medium';
};

// 编辑业务
const handleEdit = () => {
  router.push(`/dashboard/businesses?edit=${businessId.value}`);
};

// 更新进度
const handleUpdateProgress = () => {
  progressForm.businessStatus = businessDetail.value.businessStatus;
  progressForm.progressNotes = businessDetail.value.progressNotes || '';
  progressDialogVisible.value = true;
};

// 提交进度更新
const submitProgress = async () => {
  try {
    submitLoading.value = true;
    
    // 如果状态有变更，先更新状态
    if (progressForm.businessStatus !== businessDetail.value.businessStatus) {
      await updateBusinessStatus(businessId.value, progressForm.businessStatus);
    }
    
    // 更新进度备注
    await updateBusinessProgress(businessId.value, progressForm.progressNotes);
    
    ElMessage.success('业务进度更新成功');
    progressDialogVisible.value = false;
    
    // 重新获取业务详情
    getBusinessDetail();
  } catch (error) {
    console.error('更新业务进度失败:', error);
    ElMessage.error('更新业务进度失败');
  } finally {
    submitLoading.value = false;
  }
};

// 创建工单
const handleCreateWorkOrder = () => {
  // 跳转到工单创建页面，并携带业务ID参数
  router.push({
    path: '/dashboard/work-orders',
    query: { 
      create: true, 
      businessId: businessId.value,
      customerId: businessDetail.value.customerId
    }
  });
};

// 查看工单
const viewWorkOrder = (row) => {
  router.push(`/dashboard/work-orders/detail/${row.id}`);
};

onMounted(async () => {
  businessId.value = route.params.id;
  await getBusinessDetail();
  getRelatedWorkOrders();
});
</script>

<style lang="scss" scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .header-left {
    display: flex;
    align-items: center;
    
    h2 {
      font-size: 24px;
      font-weight: 600;
      color: #333;
      margin: 0;
      margin-left: 8px;
    }
  }
}

.loading-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.detail-wrapper {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h3 {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
    }
  }
  
  .progress-content {
    white-space: pre-line;
    line-height: 1.6;
    color: #333;
    padding: 10px 0;
  }
  
  .no-data {
    padding: 20px 0;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style> 